#include "querywidget.h"
#include "ui_querywidget.h"

QueryWidget::QueryWidget(QWidget *parent) :
    BaseEditor(parent),
    ui(new Ui::QueryWidget)
{
    ui->setupUi(this);

    selectIndex=IDX_None;
    queryModel=new QSqlQueryModel(this);
    ui->tableView->setModel(queryModel);
    createMenu();
}

QueryWidget::~QueryWidget()
{
    delete ui;
}

void QueryWidget::generateMenu()
{
    menu->addAction("按名称查询",this,&QueryWidget::queryByName);
    menu->addAction("按编码查询",this,&QueryWidget::queryByCode);
    menu->addSeparator();
    menu->addAction("更新视图",this,&QueryWidget::updateView);
}

void QueryWidget::queryByName()
{
    auto input=QInputDialog::getText(this,"输入名称","名称");
    if(input.isEmpty())
        return;

    QString sql=entity.queryByName().arg(input);
    query(sql);
}

void QueryWidget::queryByCode()
{
    auto input=QInputDialog::getText(this,"输入编码","编码");
    if(input.isEmpty())
        return;

    QString sql=entity.queryByCode().arg(input);
    query(sql);
}

void QueryWidget::query(const QString &sql)
{
    emit transferLog(sql);
    queryModel->setQuery(QSqlQuery(sql));
    setHeaderData();
}

void QueryWidget::prepare(int idx)
{
    selectIndex=idx;
    updateView();
}

void QueryWidget::updateView()
{
    QString fileName;
    switch (selectIndex) {
    case IDX_Department:
        fileName=P_FHS_SHARE + FN_Department;
        break;
    case IDX_Person:
        fileName=P_FHS_SHARE + FN_Person;
        break;
    case IDX_SaleOrder:
        fileName=P_FHS_SHARE + FN_SaleOrder;
        break;
    case IDX_DispatchList:
        fileName=P_FHS_SHARE + FN_DispatchList;
        break;
    case IDX_SaleBillVouch:
        fileName=P_FHS_SHARE + FN_SaleBillVouch;
        break;
    case IDX_FaCards:
        fileName=P_FHS_SHARE + FN_FaCards;
        break;
    }

    if(!QFile::exists(fileName))
    {
        QString log="缺少配置文件：" + fileName;
        transferLog(log);
        QMessageBox::warning(this,"配置文件缺失",log);
        return;
    }

    entity.setFileName(fileName);
    if(entity.load())
    {
        QString sql=entity.query();
        query(sql);
    }
    else
        QMessageBox::warning(this,"配置文件错误",
                             "无法加载配置文件！");
}

void QueryWidget::setHeaderData()
{
    QStringList items=entity.columns();
    if(items.isEmpty())
        return;
    for (int i = 0; i < items.size(); i++) {
        queryModel->setHeaderData(i,Qt::Horizontal,items.at(i));
    }
}

void QueryWidget::on_tableView_doubleClicked(const QModelIndex &index)
{
    if(index.isValid())
    {
        QString item=index.data().toString();
        if(item.isEmpty())
            return;

        qApp->clipboard()->setText(item);
        emit showMessage(item + " 已复制到粘贴板");
    }
}
